package com.tangula.voicenote.service

import android.content.Intent
import android.util.Log
import com.tangula.android.base.TglLocalServiceBinder
import com.tangula.android.base.TglService
import com.tangula.android.utils.ApplicationUtils
import com.tangula.voicenote.db.NoteDbHelper
import com.tangula.voicenote.entity.NoticeEntity

interface NoteDb{
    fun saveNotice(notice:NoticeEntity): NoticeEntity
    fun createNotice():NoticeEntity
    fun removeNotice(entity:NoticeEntity)
    fun listNotices():List<NoticeEntity>
    fun byNoticeId(id:String):NoticeEntity?

}

class DbBinder: TglLocalServiceBinder(), NoteDb{

    override fun byNoticeId(id:String): NoticeEntity?{
        return NoteDbHelper().byId(id)
    }

    override fun saveNotice(notice:NoticeEntity):NoticeEntity{
        Log.v("console", "save   ${notice.id}   ${notice.message}")
        return NoteDbHelper().save(notice)!!
    }

    override fun createNotice(): NoticeEntity {
        return NoteDbHelper().createOrSaveNote(NoticeEntity().also {
            it.color = listNotices().count()
        })
    }

    override fun removeNotice(entity: NoticeEntity) {
        NoteDbHelper().removeNote(entity)
    }

    override fun listNotices(): List<NoticeEntity> {
        return NoteDbHelper().listAllNotes() as List<NoticeEntity>
    }


}

class DatabaseService: TglService<DbBinder>() {

    companion object {
        fun exec(callback:(NoteDb)->Unit){
            TglService.bind2BackgroundService(ApplicationUtils.APP, DatabaseService::class.java,{bd->
                callback(bd as NoteDb)
            }, {_->}){}
        }
    }

    override fun onCreateBinder(intent: Intent?, flags: Int, startId: Int): DbBinder {
        return DbBinder()
    }
}